package com.harmonk.firstscene.ui.component

import android.app.Application
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.harmonk.firstscene.db.entity.TrafficEvent
import com.harmonk.firstscene.ui.model.RoadViewModel
import com.harmonk.firstscene.ui.model.RoadViewModelFactory
import com.harmonk.firstscene.ui.model.TrafficEventViewModel
import com.harmonk.firstscene.ui.model.TrafficEventViewModelFactory
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * 第一个Tab：显示并可编辑TrafficEvent的自有属性
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EventInfoTab(
    navController: NavController,
    eventId: Long,
    modifier: Modifier = Modifier
) {
    val viewModel: TrafficEventViewModel = viewModel(
        factory = TrafficEventViewModelFactory(LocalContext.current.applicationContext as Application)
    )
    val roadViewModel: RoadViewModel = viewModel(
        factory = RoadViewModelFactory(LocalContext.current.applicationContext as Application)
    )

    var eventState by remember { mutableStateOf<TrafficEvent?>(null) }
    val liveEventState by viewModel.currentEvent.observeAsState()

    val roads by roadViewModel.roads.observeAsState(emptyList())
    var roadIndexForEvent by remember { mutableIntStateOf(-1) }

    LaunchedEffect(Unit) {
        viewModel.getCurrentEvent(eventId)
        roadViewModel.loadAllRoads()
    }
    LaunchedEffect(liveEventState) {
        if (liveEventState != null) {
            eventState = liveEventState
            roadIndexForEvent = roads.indexOfFirst { it.roadId == liveEventState!!.roadId }
        }
    }

    DisposableEffect(Unit) {
        onDispose {
            eventState?.let {
                viewModel.updateTrafficEvent(it)
            }
            viewModel.loadTrafficEvents()
        }
    }

    eventState ?: return

    var showDatePicker by remember { mutableStateOf(false) }
    var showTimePicker by remember { mutableStateOf(false) }

    val datePickerState = rememberDatePickerState(
        initialSelectedDateMillis = eventState!!.timestamp
    )

    if (showDatePicker) {
        DatePickerDialog(
            onDismissRequest = { showDatePicker = false },
            confirmButton = {
                TextButton(
                    onClick = {
                        val selectedDate = datePickerState.selectedDateMillis
                        if (selectedDate != null) {
                            // 更新事件时间（只更新日期部分）
                            val calendar = Calendar.getInstance().apply {
                                timeInMillis = eventState!!.timestamp
                                val hour = get(Calendar.HOUR_OF_DAY)
                                val minute = get(Calendar.MINUTE)

                                timeInMillis = selectedDate
                                set(Calendar.HOUR_OF_DAY, hour)
                                set(Calendar.MINUTE, minute)
                                set(Calendar.SECOND, 0)
                                set(Calendar.MILLISECOND, 0)
                            }
                            eventState = eventState!!.copy(timestamp = calendar.timeInMillis)
                        }
                        showDatePicker = false
                    }
                ) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(onClick = { showDatePicker = false }) {
                    Text("取消")
                }
            }
        ) {
            DatePicker(state = datePickerState)
        }
    }

    val timePickerState = rememberTimePickerState(
        initialHour = SimpleDateFormat(
            "HH",
            Locale.getDefault()
        ).format(Date(eventState!!.timestamp)).toInt(),
        initialMinute = SimpleDateFormat("mm", Locale.getDefault()).format(
            Date(eventState!!.timestamp)
        ).toInt(),
        is24Hour = true
    )

    if (showTimePicker) {
        AlertDialog(
            onDismissRequest = { showTimePicker = false },
            title = { Text("选择时间") },
            text = {
                TimePicker(state = timePickerState)
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        // 更新事件时间（只更新时间部分）
                        val calendar = Calendar.getInstance().apply {
                            timeInMillis = eventState!!.timestamp
                            set(Calendar.HOUR_OF_DAY, timePickerState.hour)
                            set(Calendar.MINUTE, timePickerState.minute)
                            set(Calendar.SECOND, 0)
                            set(Calendar.MILLISECOND, 0)
                        }
                        eventState = eventState!!.copy(timestamp = calendar.timeInMillis)
                        showTimePicker = false
                    }
                ) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(onClick = { showTimePicker = false }) {
                    Text("取消")
                }
            }
        )
    }

    Column(
        modifier = modifier
            .background(MaterialTheme.colorScheme.background)
            .fillMaxSize()
            .padding(12.dp)
            .verticalScroll(rememberScrollState()),
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .border(
                    width = 1.dp,
                    color = MaterialTheme.colorScheme.outline,
                    shape = RoundedCornerShape(12.dp)
                )
                .padding(horizontal = 12.dp)
        ) {
            // 显示时间
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(
                    text = "时间",
                    style = MaterialTheme.typography.titleSmall,
                )
                // 填充空白
                Spacer(modifier = Modifier.weight(1f))
                TextButton(
                    onClick = { showDatePicker = true },
                ) {
                    Text(
                        SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(
                            Date(eventState!!.timestamp)
                        )
                    )
                }

                TextButton(
                    onClick = { showTimePicker = true },
                ) {
                    Text(
                        SimpleDateFormat("HH:mm", Locale.getDefault()).format(
                            Date(eventState!!.timestamp)
                        )
                    )
                }
            }

            HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

            var roadExpanded by remember { mutableStateOf(false) }
            Row(
                modifier = Modifier
                    .fillMaxWidth().height(56.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(
                    text = "道路",
                    style = MaterialTheme.typography.titleSmall,
                )
                // 填充空白
                Spacer(modifier = Modifier.weight(0.5f))
                ExposedDropdownMenuBox(
                    modifier = Modifier.weight(1f),
                    expanded = roadExpanded,
                    onExpandedChange = { roadExpanded = it },
                ) {
                    TextField(
                        // The `menuAnchor` modifier must be passed to the text field to handle
                        // expanding/collapsing the menu on click. A read-only text field has
                        // the anchor type `PrimaryNotEditable`.
                        modifier = Modifier
                            .menuAnchor(MenuAnchorType.PrimaryNotEditable),
                        textStyle = TextStyle(textAlign = TextAlign.End),
                        value = if (roadIndexForEvent == -1) "选择道路" else roads[roadIndexForEvent].name,
                        onValueChange = {},
//                        textAlign = TextAlign.End,
                        readOnly = true,
                        singleLine = true,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = roadExpanded) },
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color.Transparent,
                            unfocusedBorderColor = Color.Transparent,
                            disabledBorderColor = Color.Transparent
                        ),
                    )
                    DropdownMenu(
                        expanded = roadExpanded,
                        onDismissRequest = { roadExpanded = false },
                        modifier = Modifier.exposedDropdownSize()
                    ) {
                        for (i in roads.indices) {
                            DropdownMenuItem(
                                text = { Text(roads[i].name) },
                                onClick = {
                                    roadExpanded = false
                                    eventState = eventState!!.copy(roadId = roads[i].roadId)
                                    roadIndexForEvent = i
                                }
                            )
                            HorizontalDivider(thickness = 1.dp)
                        }
                        DropdownMenuItem(
                            text = { Text("+ 新增道路") },
                            onClick = {
                                roadExpanded = false
                                navController.navigate("road")
                            }
                        )
                    }
                }
            }

            if (roadIndexForEvent != -1) {
                HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

                Row(
                    modifier = Modifier
                        .fillMaxWidth().height(56.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Text(
                        text = "方向",
                        style = MaterialTheme.typography.titleSmall,
                    )
                    // 填充空白
                    Spacer(modifier = Modifier.weight(0.2f))
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = eventState!!.direction == 0,
                            onClick = {
                                eventState = eventState!!.copy(direction = 0)
                            }
                        )
                        Text(roads[roadIndexForEvent].upDirection)
                    }
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = eventState!!.direction == 1,
                            onClick = {
                                eventState = eventState!!.copy(direction = 1)
                            }
                        )
                        Text(roads[roadIndexForEvent].downDirection)
                    }
                }
            }

            HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

            Row(
                modifier = modifier
                    .fillMaxWidth().height(56.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                TextButton(
                    onClick = {
                        eventState = eventState!!.copy(isMainLine = !eventState!!.isMainLine)
                    },
                    // 添加边框
                    border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
                ) {
                    Text(
                        text = if (eventState!!.isMainLine) "公里桩号" else "具体位置",
                        style = MaterialTheme.typography.titleSmall
                    )
                }
//                Spacer(modifier = Modifier.weight(0.1f))

                if (eventState!!.isMainLine) {
                    Row(
                        modifier = Modifier.weight(1f),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.End
                    ) {
                        TextField(
                            modifier = modifier
                                .weight(1f),
                            value = eventState!!.kilometer.toString(),
                            onValueChange = {
                                eventState = eventState!!.copy(kilometer = it.toIntOrNull() ?: 0)
                            },
                            singleLine = true,
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Number
                            ),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            ),
                        )
                        Text(modifier = modifier.weight(0.5f), text = "公里")
                        TextField(
                            modifier = modifier
                                .weight(1f),
                            value = eventState!!.meter.toString(),
                            onValueChange = {
                                eventState = eventState!!.copy(meter = it.toIntOrNull() ?: 0)
                            },
                            singleLine = true,
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Number
                            ),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            ),
                        )
                        Text(modifier = modifier.weight(0.3f), text = "米")
                    }
                } else {
                    Row(
                        modifier = Modifier.weight(1f),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        TextField(
                            value = eventState!!.location,
                            onValueChange = {
                                eventState = eventState!!.copy(location = it)
                            },
                            placeholder = { Text("请输入位置") },
                            modifier = Modifier
                                .weight(1f),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            ),
                        )
                    }
                }
            }
        }

        Text(
            text = "简要描述:",
            modifier = Modifier.padding(top = 12.dp)
        )
        OutlinedTextField(
            value = eventState!!.brief,
            onValueChange = {
                eventState = eventState!!.copy(brief = it)
            },
            placeholder = { Text("请输入简要描述") },
            modifier = Modifier
                .fillMaxWidth(),
            shape = RoundedCornerShape(12.dp),
        )

        // 损伤情况选择
        Text(
            text = "损伤情况:",
            modifier = Modifier.padding(top = 12.dp)
        )
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .border(
                    width = 1.dp,
                    color = MaterialTheme.colorScheme.outline,
                    shape = RoundedCornerShape(12.dp)
                )
                .padding(horizontal = 12.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                Text("车辆损失")
                Checkbox(
                    checked = eventState!!.haveVehicleDamage,
                    onCheckedChange = {
                        eventState = eventState!!.copy(haveVehicleDamage = it)
                    }
                )
            }
            // 添加分割线
            HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                Text("人员受伤")
                Checkbox(
                    checked = eventState!!.haveInjuries,
                    onCheckedChange = {
                        eventState = eventState!!.copy(haveInjuries = it)
                    }
                )
            }
            HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                Text("路产损失")
                Checkbox(
                    checked = eventState!!.haveRoadPropertyLoss,
                    onCheckedChange = {
                        eventState = eventState!!.copy(haveRoadPropertyLoss = it)
                    }
                )
            }
            HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                Text("货物损失")
                Checkbox(
                    checked = eventState!!.haveGoodsLoss,
                    onCheckedChange = {
                        eventState = eventState!!.copy(haveGoodsLoss = it)
                    }
                )
            }
            HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                Text("施救费用")
                Checkbox(
                    checked = eventState!!.haveRescueExpenses,
                    onCheckedChange = {
                        eventState = eventState!!.copy(haveRescueExpenses = it)
                    }
                )
            }
        }
    }
}
